package com.cainiao.stock.helper;

import com.cainiao.stock.enums.CodeEnum;
import com.cainiao.stock.response.ResponseResult;
import com.google.common.util.concurrent.RateLimiter;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;



@Aspect
@Component
@SuppressWarnings("all")
public class LimiterAspect {

    private final RateLimiter rateLimiter;

    public LimiterAspect(RateLimiter rateLimiter) {
        this.rateLimiter = rateLimiter;
    }

    @Pointcut(value = "@annotation(com.cainiao.stock.annotation.Limiter)")
    public void pt(){};

    @Around(value = "pt()")
    public Object limiter(ProceedingJoinPoint pjp) throws Throwable{
        //流量
        boolean flag= rateLimiter.tryAcquire();
        if (flag){
            return pjp.proceed();
        }else {
            return ResponseResult.error(CodeEnum.OVER_CONCURRENT_NUM);
        }
    }
}
